package video

import (
	"dy/internal/configs/config"
	"dy/pkg/code"
	"dy/pkg/cover"
	"dy/pkg/jwt"
	"fmt"
	"path/filepath"
	"strconv"
	"time"

	"github.com/disintegration/imaging"
	"github.com/gin-gonic/gin"
)

func (u *ControllerVideo) PublishAction(ctx *gin.Context) {
	type param struct {
		Token string `form:"token" json:"token" binding:"required"`
		Title string `form:"title" json:"title" binding:"required"`
	}

	var request param
	err := ctx.Bind(&request)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	//解析token
	userId, err := jwt.ParseToken(request.Token)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	//保存视频
	data, err := ctx.FormFile("data")
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}
	// filename := filepath.Base(data.Filename)
	filename := filepath.Base(strconv.FormatInt(time.Now().Unix(), 10))
	finalName := fmt.Sprintf("%d%s.mp4", userId, filename)
	videoSaveFile := filepath.Join("./buffer/video/", finalName)
	err = ctx.SaveUploadedFile(data, videoSaveFile)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	reader := cover.ReadFrameAsJpeg(videoSaveFile, 1)
	img, err := imaging.Decode(reader)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}
	imageName := fmt.Sprintf("%d%s.jpg", userId, filename)
	imgSaveFile := filepath.Join("./buffer/img/", imageName)
	err = imaging.Save(img, imgSaveFile)

	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	search := map[string]interface{}{}
	search["play_url"] = "http://" + config.Conf.UserWeb.Host + ":" + config.Conf.UserWeb.FilePort + "/douyin/" + videoSaveFile
	search["cover_url"] = "http://" + config.Conf.UserWeb.Host + ":" + config.Conf.UserWeb.FilePort + "/douyin/" + imgSaveFile
	search["title"] = request.Title
	search["author_id"] = userId
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	err = u.srv.Video().Add(ctx, search)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	ctx.JSON(200, gin.H{
		"status_code": 0,
		"status_msg":  "success",
	})
}
